package com.rp.configure.controller;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rp.common.result.ResultDTO;
import com.rp.common.utils.ModBusCode;
import com.rp.common.utils.NullIs;
import com.rp.common.utils.Selectway;
import com.rp.configure.entity.*;
import com.rp.configure.service.OperationService;
import com.rp.configure.service.SvgOperationService;
import com.rp.configure.service.SvgService;
import com.rp.data.tcp_ws.server_tcp.ServerHandlerTcp;
import io.netty.channel.Channel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author vicente
 * @since 2021-07-27
 */
@RestController
@RequestMapping("/svg-operation")
@Api("svg操作控制")
public class SvgOperationController {
    @Autowired
    private SvgOperationService svgOperationService;
    @Autowired
    private OperationService OperationService;

    @ApiOperation(value = "根据项目id和svg_id查询单个")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    @GetMapping(value = "/one")
    public ResultDTO<SvgOperation> list(@RequestParam(value = "subjectId") String subjectId,
                                        @RequestParam(value = "svgId") String svgId
    ) {
        QueryWrapper<SvgOperation> queryWrapper = new QueryWrapper<SvgOperation>();
        queryWrapper.eq("subject_id", subjectId).eq("svg_id", svgId);
        SvgOperation svgOperation = svgOperationService.getOneBySvgId(queryWrapper);
        String operationId = svgOperation.getOperationId();
        JSONArray array = JSONArray.parseArray(operationId);
        QueryWrapper<Operation> queryWrapper1 = new QueryWrapper<Operation>();
        queryWrapper.in("operation_id", array).select("id", "name").orderByAsc("rank");
        svgOperation.setOperations(OperationService.list(queryWrapper1));
        return ResultDTO.success().data(svgOperation);
    }

    @PostMapping("/insert")
    @ApiOperation(value = "增加")
    @Transactional
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    public ResultDTO insert(@RequestBody SvgOperation svgOperation) {


        Object json1 = JSON.toJSON(svgOperation.getOperationId());
        svgOperation.setOperationId(json1.toString());
        return ResultDTO.tf(svgOperationService.save(svgOperation));
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    public ResultDTO update(@RequestBody SvgOperation svgOperation) {
        Object json1 = JSON.toJSON(svgOperation.getOperationId());
        svgOperation.setOperationId(json1.toString());
        return ResultDTO.tf(svgOperationService.updateById(svgOperation));
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    public ResultDTO delete(@RequestBody @ApiParam(value = "id", required = true) String id) {
        return ResultDTO.tf(svgOperationService.removeById(id));
    }

    @GetMapping("/operation")
    @ApiOperation(value = "操作")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    public ResultDTO operation(@RequestParam(value = "subjectId") String subjectId,
                               @RequestParam(value = "svgId") String svgId) {
        QueryWrapper<SvgOperation> queryWrapper = new QueryWrapper<SvgOperation>();
        queryWrapper.eq("subject_id", subjectId).eq("svg_id", svgId);
        SvgOperation svgOperation = svgOperationService.getOneBySvgId(queryWrapper);
        String operationId = svgOperation.getOperationId();
        JSONArray array = JSONArray.parseArray(operationId);
        QueryWrapper<Operation> queryWrapper1 = new QueryWrapper<Operation>();
        queryWrapper.in("operation_id", array).select("id", "name").orderByAsc("rank1");
        List<Operation> list = OperationService.list(queryWrapper1);
        Set<Map.Entry<Channel, String>> entries = ServerHandlerTcp.mapChannel.entrySet();
        Iterator<Map.Entry<Channel, String>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<Channel, String> next = iterator.next();
            if (next.getValue().equals(svgOperation.getGatewayId())) {
                Channel key = next.getKey();
                for (Operation op : list
                ) {
                    switch (op.getAgreement()) {
                        case 5:
                            key.writeAndFlush(ModBusCode.writeSingleCoil(op.getSlaveAddress(), op.getStartAddress(), op.getState()));
                            break;
                    }
                }
            }
        }
        return ResultDTO.tf(true);
    }

    @GetMapping("/operation1")
    @ApiOperation(value = "自定义操作操作")
//    @RequiresRoles(value={"admin","vip"},logical = Logical.OR)
    public ResultDTO operation1(@RequestParam(value = "gatewayId") String gatewayId,
                               @RequestParam(value = "operationId") String operationId,
                                @RequestParam(value = "state",required = false) Integer state) {

        Set<Map.Entry<Channel, String>> entries = ServerHandlerTcp.mapChannel.entrySet();
        Iterator<Map.Entry<Channel, String>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<Channel, String> next = iterator.next();
            if (next.getValue().equals(gatewayId)) {
                Channel key = next.getKey();
                Operation byId = OperationService.getById(operationId);
                if (!NullIs.isEmpty(state)){

                }
                switch (byId.getAgreement()) {
                    case 5:
                        key.writeAndFlush(ModBusCode.writeSingleCoil(byId.getSlaveAddress(), byId.getStartAddress(), byId.getState()));
                        break;

                }
            }
        }
        return ResultDTO.tf(true);
    }

}
